import {
    _decorator,
    Camera,
    Component,
    director,
    gfx,
    Layers,
    Material,
    MeshRenderer,
    Node,
    RenderTexture,
    screen,
    Texture2D,
} from "cc";
import { gameShaderCase } from "../../../GameShaderCase";
const { ccclass, property } = _decorator;

@ccclass("ShaderCaseMirror")
export class ShaderCaseMirror extends Component {
    private _camera: Camera = null;
    private _mat: Material = null;

    protected onLoad(): void {
        this._mat = this.node.getComponent(MeshRenderer)?.getMaterialInstance(0);
        this._createCamera();
        this._createRenderTexture();
    }

    update(deltaTime: number) {}

    /**
     * 创建相机
     */
    private _createCamera(): void {
        this._destroyCamera();
        const mainCamera = gameShaderCase.globalMgr.mainCamera;
        const node = new Node("mirrorCamera");

        this._camera = node.addComponent(Camera);
        this._camera.clearFlags = Camera.ClearFlag.DEPTH_ONLY;
        this._camera.priority = mainCamera.priority - 1;
        this._camera.visibility = Layers.nameToLayer("Map") | Layers.nameToLayer("Role");
        this._camera.node.setPosition(mainCamera.node.position);
        this._camera.node.setRotation(mainCamera.node.rotation);
        director.getScene().addChild(node);
    }

    /**
     * 创建渲染纹理
     */
    private _createRenderTexture(): void {
        // return;
        const texture = new RenderTexture();
        const size = screen.windowSize;

        texture.reset({
            width: size.width,
            height: size.height,
            passInfo: new gfx.RenderPassInfo(
                [new gfx.ColorAttachment(gfx.Format.RGBA8)],
                new gfx.DepthStencilAttachment(gfx.Format.DEPTH_STENCIL)
            ),
        });
        texture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR);
        texture.setWrapMode(Texture2D.WrapMode.MIRRORED_REPEAT, Texture2D.WrapMode.MIRRORED_REPEAT);

        this._camera.targetTexture = texture;

        this._mat.setProperty("mainTexture", texture);
    }

    /**
     * 销毁相机
     */
    private _destroyCamera(): void {
        if (this._camera) {
            this._camera.targetTexture?.destroy();
            this._camera.node.destroy();
            this._camera = null;
        }
    }
}
